package top.techqi.hamtools.drawable

import android.graphics.*
import android.graphics.drawable.Drawable
import top.techqi.hamtools.ext.toRectF

class SweepDrawable(private val src: Drawable, private var fDegrees: Float, private var tDegrees: Float)
    : Drawable(), Drawable.Callback {
    private val path = Path()
    private val paint = Paint()

    init {
        paint.color = Color.GREEN
        paint.strokeWidth = 5f
    }

    override fun getIntrinsicWidth() = src.intrinsicWidth
    override fun getIntrinsicHeight() = src.intrinsicHeight
    override fun setAlpha(alpha: Int) = src.setAlpha(alpha)
    override fun getOpacity() = src.opacity
    override fun setColorFilter(colorFilter: ColorFilter?) = src.setColorFilter(colorFilter)

    override fun scheduleDrawable(who: Drawable?, what: Runnable?, `when`: Long) = src.scheduleSelf(what, `when`)
    override fun unscheduleDrawable(who: Drawable?, what: Runnable?) = src.unscheduleSelf(what)
    override fun invalidateDrawable(who: Drawable?) = invalidateSelf()

    override fun onBoundsChange(bounds: Rect) {
        src.bounds = bounds
    }

    override fun onLevelChange(level: Int): Boolean {
        super.onLevelChange(level)
        val sweep = (tDegrees - fDegrees) * level / MAX_LEVEL
        path.reset()
        path.addArc(bounds.toRectF(), fDegrees, sweep)
        path.lineTo(bounds.exactCenterX(), bounds.exactCenterY())
        path.close()
        invalidateSelf()
        return true
    }

    override fun draw(canvas: Canvas) {
        val count = canvas.saveCount
        canvas.clipPath(path)
        src.draw(canvas)
        canvas.restoreToCount(count)
    }

    companion object {
        private val MAX_LEVEL = 10000
    }
}